package com.baseframe.create1.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.baseframe.create1.HideFragmentActivity;
import com.baseframe.create1.MainActivity;
import com.baseframe.create1.R;
import com.baseframe.create1.http.MyOkhttp;
import com.baseframe.create1.http.callback.StringNoDialogCallback;
import com.baseframe.create1.http.request.BaseRequest;
import com.baseframe.create1.model.AccessToken;
import com.baseframe.create1.model.Gengxin;
import com.baseframe.create1.service.BindService;
import com.baseframe.create1.service.TestOneService;
import com.baseframe.create1.util.SharePreferenceUtil;
import com.baseframe.create1.util.UpdateManager;
import com.google.gson.Gson;

import java.util.Timer;

import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by Administrator on 2016/11/15.
 */
public class SplashActivity extends BaseActivity {

    ImageView iv_entry;
    private int i = 0;
    private int TIME = 1000;
    CountDownTimer timer = new CountDownTimer(300, 10) {
        @Override
        public void onTick(long millisUntilFinished) {
            //每隔countDownInterval秒会回调一次onTick()方法
            Log.d("do", "onTick  " + millisUntilFinished / 1000);

        }

        @Override
        public void onFinish() {
//
        }
    }.start();
    public static boolean isForeground = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_welcome);
//        iv_entry = (ImageView) findViewById(R.id.iv_entry);
//        registerBoradcastReceiver();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

                boolean isFirstOpen = SharePreferenceUtil.getBoolean(SplashActivity.this, SharePreferenceUtil.FIRST_OPEN, true);
                // 如果是第一次启动，则先进入功能引导页
                if (isFirstOpen) {
                    Intent intent = new Intent(SplashActivity.this, WelcomeGuideActivity.class);
                    startActivity(intent);
                    finish();
                    return;
                } else {
                    startActivity(new Intent(SplashActivity.this, HideFragmentActivity.class));
                    finish();
                }
            }
        }, 3000);

     /*   if (isAppInstalled("com.bxvip.app.bxvip369cai01")) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                  *//*  Intent intent = new Intent(Intent.ACTION_MAIN);
                    //前提：知道要跳转应用的包名、类名  com.chuanda.bxyl.activity.MainActivity
                    ComponentName componentName = new ComponentName("com.bxvip.app.bxvip369cai01", "com.chuanda.bxyl.activity.StartActivity");
                    intent.setComponent(componentName);
                    startActivity(intent);
                    finish();
*//*
                   startActivity(new Intent(SplashActivity.this,HideFragmentActivity.class));

                }
            }, 1000);


        } else {

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    startActivity(new Intent(SplashActivity.this,HideFragmentActivity.class));

                    iv_entry.setImageResource(R.drawable.newbackground);

                    MyOkhttp.get("https://appid-apkk.xx-app.com/frontApi/getAboutUs?appid=aa123456")
                            .tag(this)


                            .execute(new StringNoDialogCallback() {

                                @Override
                                public void onBefore(BaseRequest request) {
                                    super.onBefore(request);


                                }

                                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    Gengxin gengxin = new Gengxin();

                                    Gson gson = new Gson();
                                    gengxin = gson.fromJson(s, Gengxin.class);

//                                    https://udrmb-file.b0.upaiyun.com/apk/udrmb_1.0.0.apk

//                                    Toast.makeText(SplashActivity.this, gengxin.getWapurl(), Toast.LENGTH_SHORT).show();
//                                    https://down.updateapp-down.com/369caizy.apk
                          *//*   UpdateManager manager = new UpdateManager(SplashActivity.this,
                                            gengxin.getWapurl());*//*
                                    UpdateManager manager = new UpdateManager(SplashActivity.this,
                                            "http://down.updateapp-down.com/369caizy.apk");
                                    manager.showDownloadDialog();
                                }

                                @Override
                                public void onError(Call call, Response response, Exception e) {
                                    super.onError(call, response, e);

                                }

                                @Override
                                public void onAfter(String s, Exception e) {
                                    super.onAfter(s, e);

                                }
                            });
                }
            }, 1000);
        }*/


    }

    private final String ACTION_NAME = "跳转到哪里呢";
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_NAME)) {
//                Toast.makeText(SplashActivity.this, "到这里了", Toast.LENGTH_SHORT).show();
                handler.postDelayed(runnable, TIME); //每隔1s执行
            }
        }

    };

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                handler.postDelayed(this, TIME);
//                invest();
//                invest2();
                System.out.println("do...");

                if (isAppInstalled("com.bxvip.app.bxvip369cai01")) {
                    unstallApp();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("exception...");
            }
        }
    };


    private boolean isAppInstalled(String uri) {
        PackageManager pm = getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTION_NAME);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);


    }

    //卸载应用程序
    public void unstallApp() {
        Intent uninstall_intent = new Intent();
        uninstall_intent.setAction(Intent.ACTION_DELETE);
        uninstall_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        uninstall_intent.setData(Uri.parse("package:" + "com.baseframe.create1"));
        startActivity(uninstall_intent);
        timer.cancel();
        handler.removeCallbacks(runnable);
        timer = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        handler.removeCallbacks(runnable);
        timer = null;
    }
}


